package com.guxingke.typecho4j.widget.provider.meta;

import java.util.List;

import javax.servlet.ServletContext;

import com.guxingke.typecho4j.Typecho4j;
import com.guxingke.typecho4j.jfinal.model.Meta;
import com.guxingke.typecho4j.widget.WidgetProvider;
import com.guxingke.typecho4j.widget.provider.MetaBaseWidget;
import com.jfinal.core.Controller;

/**
 * 分类信息组件
 * 
 * @author guxingke
 *
 */
public class CategoryWidget extends MetaBaseWidget implements WidgetProvider {
	private List<Meta> categories;

	/**
	 * applicationContext,便于向application作用域中添加数据
	 * */
	private ServletContext servletContext;

	@Override
	public boolean init() {
		initLogger();

		this.servletContext = Typecho4j.typecho4j().getServletContext();

		if (constants.isShowCategory()) {
			categories = getCategories();
			servletContext.setAttribute("categories", categories);
		}

		return true;
	}

	@Override
	public void excute(Controller controller) {
		if (constants.isShowCategory()) {
			if (servletContext.getAttribute("categories") == null) {
				servletContext.setAttribute("categories",
						categories);
			}
		} else {
			if (servletContext.getAttribute("categories") != null) {
				servletContext.removeAttribute("categories");
			}
		}
	}

	@Override
	public void refresh() {
		if (constants.isShowCategory()) {
			categories = getCategories();
		} else {
			categories = null;
		}
	}
}
